<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/2/5
 * Time: 16:00
 */

namespace App\Http\Controllers\Api\V1;


use App\Http\Controllers\Api\ApiBase;
use App\Models\WxUser;
use App\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class AuthController extends ApiBase
{
    /**
     * @param Request $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     */
    public function wx_login(Request $request)
    {
        $user = $this->getUser();

        if ($user) {
            //return $this->failed('已登录');
        }
        $validator = \Validator::make($request->all(), [
            'code' => ['required'],
            'iv' => 'required',
            'encryptedData' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $code = $request->input("code");
        $iv = $request->input("iv");
        $encryptedData = $request->input("encryptedData");
        $config = [
            'app_id' => config('wx.app_id'),
            'secret' => config('wx.secret'),
            'response_type' => 'array',
        ];
        try {
            $app = Factory::miniProgram($config);
            $sessionKey = $app->auth->session($code);
            logger("sessionKey",$sessionKey);
            $obj = $app->encryptor->decryptData($sessionKey['session_key'], $iv, $encryptedData);
        } catch (\Exception $exception) {
            return $this->failed('登录失败');
        }


        $wx_user = WxUser::query()->updateOrCreate(['open_id' => $obj['openId']], [
            'open_id' => $obj['openId'],
            'nick_name' => $obj['nickName'],
            'avatar' => $obj['avatarUrl'],
            'country' => $obj['country'],
            'province' => $obj['province'],
            'city' => $obj['city'],
            'gender' => $obj['gender'],
            'language' => $obj['language'],
        ]);

        $force_bind_phone = config('user.login_bind_phone', 'off');
        if ($force_bind_phone == 'on' && $wx_user->user_id == 0) {//新用户 强制绑定手机
            return $this->success($this->_re_bind_phone($wx_user));
        } elseif ($wx_user->user_id == 0) {//添加用户数据
            $user = User::addWxUser($wx_user);
        } else {
            $user = $wx_user->user;
            $user->avatar = $wx_user->avatar;
            //$user->name = $wx_user->nick_name;
            $user->save();
            if ($force_bind_phone == 'on' && empty($user->phone)) {
                return $this->success($this->_re_bind_phone($wx_user));
            }
        }
        $data['user'] = \App\Http\Resources\User::make($user)->hide(['is_follow']);
        $data['token'] = $user->createToken($user->id, ['wx-app'])->accessToken;

        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function bind_login(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'id' => 'required',
            'code' => ['required'],
            'iv' => 'required',
            'encryptedData' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $code = $request->input("code");
        $iv = $request->input("iv");
        $encryptedData = $request->input("encryptedData");
        $config = [
            'app_id' => config('wx.app_id'),
            'secret' => config('wx.secret'),
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $sessionKey = $app->auth->session($code);
        logger('sessionKey',$sessionKey);
        $obj = $app->encryptor->decryptData($sessionKey['session_key'], $iv, $encryptedData);
        $id = $this->getId();
        $wx_user = WxUser::query()->find($id);
        if ($wx_user->user_id == 0) {
            $user = User::addWxUser($wx_user, $obj['phoneNumber']);
        } else {
            $user = $wx_user->user;
            $user->phone = $obj['phoneNumber'];
            $user->save();
        }
        $data['user'] = \App\Http\Resources\User::make($user);
        $data['token'] = $user->createToken($user->id, ['wx-app'])->accessToken;
        return $this->success($data);
    }


    private function _re_bind_phone($wx_user)
    {
        return [
            'bind_phone' => true,
            'bind_text' => config('bind_phone_text', '为了您的账户安全，请先绑定手机'),
            'id' => hashid_encode($wx_user->id)
        ];
    }

}